/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'prefix',
			title : '前缀名',
			type : 'LineEdit',
			property : {tool_tip : '前缀名,默认是org-'},
		},
		{
			name:"step",
			title:"step名称",
			type:"LineEdit",
			property:{tool_tip:"step名称,默认orig"}
		},
		{
			name : 'suffix',
			title : '后缀名',
			type : 'LineEdit',
			property : {tool_tip : '后缀名,默认没有'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-08-31 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 备份层 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 前缀后缀 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>备份层");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];
try {
    var par = PAR;
	var default_par = {
		step: "orig",
		prefix: "org-",
		suffix: "",
		auto_save: "No",
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}

	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	// 检查料号是否存在
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	// 检查料号是否被打开
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
	// 检查料号是否能够check out
	if(mode=="aimdfm"){
		if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
		GEN.checkInout({job:job,mode:"out"});
	}

	if(!GEN.isStepExists({job:job, step:par.step})){
		throw "step"+par.step+"不存在"
	}

	
	GEN.openMatrix({job:job})

	rmEmpty(job)   // 删除空层
	// 通过matrix获取board层
	var layers = [];
	var spLayers = []; // 部分特殊层 ->  更改为misc层
	var matrix = GEN.getMatrix({job:job})
	// var lastBoard, lastLayer;  // 最后的board层和最后的层
	var board_layers = Object.keys(matrix).reduce(function(a,b){
		if(matrix[b].context == "board"){
			a.push(b)
			// lastBoard = b
		} else if(!/---/.test(b)){
			var reg = new RegExp("^"+par.prefix,"ig")
			if(!reg.test(b)){
				spLayers.push(b)
			}
		}
		if((b == "gtp" || b == "gbp")){
			layers.push({layer:b,row: matrix[b].row})
		}
		// lastLayer=b
		return a
	},[])
	// bfks-----及bfjs------
	// if(GEN.isLayerExists({job:job, layer:"---"})){GEN.deleteLayer({job:job, layer:["---"]})}
	
	if(GEN.isLayerExists({job:job, layer:"bfks-----"})){delLayer(job,"bfks-----")}
	if(GEN.isLayerExists({job:job, layer:"bfjs------"})){delLayer(job,"bfjs------")}
	// if(lastBoard){GEN.matrixAddLayer({job:job,layer:"---",context:'misc',after:lastBoard})}
	bk_layers = board_layers.concat(spLayers);
	bk_layers.forEach(function(layer){  // 添加备份的bk_layers
		var new_layer = par.prefix + layer + par.suffix;
		if(GEN.isLayerExists({job:job, layer:new_layer})){delLayer(job,new_layer)}
	})

	GEN.matrixAddLayer({job:job,layer:"bfks-----",type:'document',context:'misc',polarity:'positive'})

	// if(lastLayer){GEN.matrixAddLayer({job:job,layer:"bfks-----",context:'misc',after:lastLayer})}
	
	layers.sort(function(b, a){return Number(a.row - b.row)}) // 将gbp gtp下移到bfks-----下
	layers.forEach(function(item){
		var layer = item.layer
		if(GEN.isLayerExists({job:job, layer:layer})){
			GEN.matrixLayerAttr({job:job,layer:layer,context:"misc"})
			var tmp_matrix = GEN.getMatrix({job:job})
			var targetRow = Object.keys(tmp_matrix).filter(function(key){return key == "bfks-----"}).map(function(v){return tmp_matrix[v].row})
			GEN.COM("matrix_move_row,job="+job+",matrix=matrix,row="+item.row+",ins_row="+targetRow)
			GEN.COM("matrix_move_row,job="+job+",matrix=matrix,row="+targetRow+",ins_row="+(targetRow-1))
		}
	})
	bk_layers.forEach(function(layer){  // 添加备份的bk_layers
		var new_layer = par.prefix + layer + par.suffix;
		GEN.COM("matrix_copy_row,job="+job+",matrix=matrix,row="+getRow(job,layer)+",ins_row=" + (Number(getRow(job,getLastLayer(job)))+1))
		GEN.COM("matrix_rename_layer,job="+job+",matrix=matrix,layer="+layer+"+1,new_name=" + new_layer)
		GEN.COM("matrix_layer_context,job="+job+",matrix=matrix,layer="+new_layer+",context=misc")

		// GEN.matrixCopyLayer({job:job,layer:layer,new_name:new_layer,after:getLastLayer(job)})
		// GEN.copyLayer({source_job:job,source_step:par.step,source_layer:layer,dest_layer:new_layer})
	})
	GEN.matrixAddLayer({job:job,layer:"bfjs------",context:'misc'})
	
	

	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function rmEmpty(job) {
	var matrix = GEN.getMatrix({job:job})
	var matrix_keys = Object.keys(matrix)  // 获取层名称数组
	var rows = matrix_keys.length  // 获取层数量
	var last_row = matrix[matrix_keys[matrix_keys.length - 1]].row  // 获取最后一层的row
	if( rows != last_row) {  // 最后一层测row跟层数量不同 说明中间有空层
		matrix_keys.forEach(function(key, i) {  // 将层按照层数组顺序移动
			var info = matrix[key]
			if( (i+1) != info.row) {
				GEN.COM("matrix_move_row,job="+job+",matrix=matrix,row="+info.row+",ins_row=" + (i + 1))
				GEN.COM("matrix_refresh,job="+job+",matrix=matrix")
			}
		})
	}
}

function getLastLayer(job){
	var layers = Object.keys(GEN.getMatrix({job:job}));
	return layers.pop()
}

function delLayer(job, layer){
	var matrix = GEN.getMatrix({job:job});
	for (var key in matrix) {
		var info = matrix[key]
		if(info.name == layer){
			GEN.COM("matrix_delete_row,job="+job+",matrix=matrix,row="+info.row)
		}
	}
}

function getRow(job, layer){
	var matrix = GEN.getMatrix({job:job});
	for (var key in matrix) {
		var info = matrix[key]
		if(info.name == layer){
			return info.row
		}
	}
}